package de.medieninf.sensimg;

import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.TextBox;
import javax.microedition.lcdui.TextField;

/**
 * Visualization of the log.
 * @author pb
 */
public class LogDisplayable extends TextBox {
    /**
     * Number of messages to be put in the textBox.
     */
    static final int NO_LAST_LOG_MESSAGES = 20;
    /**
     * Maximal number of characters in the textField.
     */
    static final int NO_CHARS_IN_TEXTFIELD = 4096;

    /**
     * Command to empty the visualization and the underlying data.
     */
    private Command cmdClear = new Command("Clear", Command.OK, 1);
    /**
     * Command to refresh the contents to the textBox.
     */
    private Command cmdUpdate = new Command("Update", Command.OK, 1);
    /**
     * The commandListener of the calling Displayable or MIDlet.
     */
    private CommandListener upperCl;
    /**
     * The local CommandListener.
     */
    private CommandListener cl = new CommandListener() {
        public void commandAction(final Command c, final Displayable d) {
            if (c == cmdClear) {
                LogDisplayable.this.setString("");
            } else if (c == cmdUpdate) {
                update();
            } else {
                upperCl.commandAction(c, d);
            }
        }
    };

    /**
     * Construct an instance of the visualization of the logger.
     * @param pupperCl upper CommandListener
     * @param cmds Command[] for Commands handled by caller
     */
    public LogDisplayable(final CommandListener pupperCl,
                          final Command[] cmds) {
        super("Logger", "", NO_CHARS_IN_TEXTFIELD, TextField.ANY);
        this.upperCl = pupperCl;
        for (int i = 0; i < cmds.length; i++) {
            addCommand(cmds[i]);
        }
        addCommand(cmdClear);
        addCommand(cmdUpdate);
        this.setCommandListener(cl);
    }

    /**
     * Inserts the last couple of log messages to display them.
     */
    public final void update() {
        String msgs = Logger.getLast(NO_LAST_LOG_MESSAGES);
        LogDisplayable.this.setString(msgs);
    }
}
